<template>
  <div class="robot-service-page">
    <div class="header">
      <h2>机器人客服配置</h2>
    </div>
    <el-card class="settings-card">
      <h3>基础设置</h3>
      <el-form :model="baseConfig" label-width="80px">
        <el-form-item label="欢迎语" class="editor-form-item">
          <quill-editor v-model:content="baseConfig.welcome" contentType="html" theme="snow" style="min-height:80px" />
        </el-form-item>
        <el-form-item label="兜底回复" class="editor-form-item">
          <quill-editor v-model:content="baseConfig.fallback" contentType="html" theme="snow" style="min-height:80px" />
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="rules-card">
      <div class="rules-header">
        <h3>自动回复规则</h3>
        <el-button type="primary" @click="showRuleDialog = true">新增规则</el-button>
      </div>
      <el-table :data="rules" border stripe style="width: 100%; margin-top: 12px;">
        <el-table-column prop="keyword" label="关键词" width="180" />
        <el-table-column prop="answerType" label="答案类型" width="120">
          <template #default="{ row }">
            <el-tag>{{ answerTypeMap[row.answerType] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="answer" label="答案内容" />
        <el-table-column prop="guides" label="引导问题">
          <template #default="{ row }">
            <el-tag v-for="g in row.guides" :key="g" type="info" style="margin-right:4px;">{{ g }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="{ row, $index }">
            <el-button size="small" @click="editRule(row, $index)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRule($index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card class="test-card">
      <div class="test-header">
        <h3>模拟对话测试</h3>
        <el-radio-group v-model="scene" size="small" style="margin-left: 16px;">
          <el-radio-button value="pc">PC端</el-radio-button>
          <el-radio-button value="h5">H5端</el-radio-button>
        </el-radio-group>
      </div>
      <div :class="['chat-window', scene]">
        <div v-for="(msg, idx) in chatHistory" :key="idx" :class="['msg-row', msg.from]">
          <div class="msg-bubble">
            <template v-if="msg.type === 'text' && msg.from === 'robot' && msg.isWelcome">
              <span v-html="msg.text"></span>
            </template>
            <template v-else-if="msg.type === 'text' && msg.from === 'robot' && msg.isFallback">
              <span v-html="msg.text"></span>
            </template>
            <template v-else-if="msg.type === 'text'">
              <span>{{ msg.text }}</span>
            </template>
            <template v-else-if="msg.type === 'emoji'">
              <span class="emoji">{{ msg.text }}</span>
            </template>
            <template v-else-if="msg.type === 'image'">
              <img :src="msg.url" class="chat-img" />
            </template>
            <template v-else-if="msg.type === 'audio'">
              <audio :src="msg.url" controls class="chat-audio" />
            </template>
            <template v-else-if="msg.type === 'video'">
              <video :src="msg.url" controls class="chat-video" />
            </template>
            <div v-if="msg.from === 'robot' && msg.guides && msg.guides.length" class="guide-btns">
              <el-button
                v-for="g in msg.guides"
                :key="g"
                size="small"
                type="info"
                class="guide-btn"
                @click="handleGuideClick(g)"
              >{{ g }}</el-button>
            </div>
          </div>
        </div>
      </div>
      <div class="chat-input-bar">
        <el-input v-model="testInput" placeholder="请输入用户问题" style="width: 220px; margin-right: 8px;" @keyup.enter="handleTest" />
        <el-button @click="showEmojiPanel = !showEmojiPanel" circle size="small">😀</el-button>
        <input ref="imgInput" type="file" accept="image/*" style="display:none" @change="onImgChange" />
        <el-button :icon="Picture" circle size="small" @click="triggerImgUpload" />
        <input ref="audioInput" type="file" accept="audio/*" style="display:none" @change="onAudioChange" />
        <el-button :icon="Microphone" circle size="small" @click="triggerAudioUpload" />
        <input ref="videoInput" type="file" accept="video/*" style="display:none" @change="onVideoChange" />
        <el-button :icon="VideoCamera" circle size="small" @click="triggerVideoUpload" />
        <el-button type="primary" @click="handleTest">发送</el-button>
        <el-button @click="resetChat" style="margin-left: 8px;">清空对话</el-button>
      </div>
      <div v-if="showEmojiPanel" class="emoji-panel">
        <span v-for="emoji in emojiList" :key="emoji" class="emoji-item" @click="sendEmoji(emoji)">{{ emoji }}</span>
      </div>
    </el-card>
    <el-dialog v-model="showRuleDialog" title="编辑自动回复规则" width="500px">
      <el-form :model="editRuleForm" label-width="80px">
        <el-form-item label="关键词">
          <el-input v-model="editRuleForm.keyword" placeholder="多个关键词用逗号分隔" />
        </el-form-item>
        <el-form-item label="答案类型">
          <el-select v-model="editRuleForm.answerType" placeholder="请选择">
            <el-option label="文本" value="text" />
            <el-option label="知识库" value="kb" />
            <el-option label="快捷回复" value="quick" />
          </el-select>
        </el-form-item>
        <el-form-item label="答案内容">
          <el-input v-if="editRuleForm.answerType === 'text'" v-model="editRuleForm.answer" placeholder="请输入答案文本" />
          <el-select v-else-if="editRuleForm.answerType === 'kb'" v-model="editRuleForm.answer" placeholder="请选择知识库文章" style="width:100%">
            <el-option v-for="item in knowledgeBaseArticles" :key="item.id" :label="item.title" :value="item.content" />
          </el-select>
          <el-select v-else-if="editRuleForm.answerType === 'quick'" v-model="editRuleForm.answer" placeholder="请选择快捷回复" style="width:100%">
            <el-option v-for="item in quickReplies" :key="item.id" :label="item.content" :value="item.content" />
          </el-select>
        </el-form-item>
        <el-form-item label="引导问题">
          <el-select v-model="editRuleForm.guides" multiple filterable allow-create default-first-option placeholder="可设置多个引导问题">
            <el-option v-for="g in guideOptions" :key="g" :label="g" :value="g" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showRuleDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRule">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';
import { QuillEditor } from '@vueup/vue-quill';
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import {
  Picture,
  Microphone,
  VideoCamera,
} from '@element-plus/icons-vue'

const baseConfig = ref({
  welcome: '您好，我是智能机器人，有什么可以帮您？',
  fallback: '很抱歉，我暂时无法理解您的问题，请换个问法或联系人工客服。'
});
const rules = ref([
  { keyword: '你好', answerType: 'text', answer: '您好，有什么可以帮您？', guides: ['如何下单', '如何联系客服'] },
  { keyword: '退货', answerType: 'kb', answer: '退货流程请参考知识库：退货政策', guides: ['退货政策', '退款时效'] },
  { keyword: '优惠券', answerType: 'quick', answer: '您可以在个人中心-优惠券中查看和领取。', guides: [] },
]);

const knowledgeBaseArticles = ref([
  { id: 'KB001', title: '退货政策详解', content: '我们的退货政策是7天无理由退货，具体细则请参考...' },
  { id: 'KB002', title: '如何申请发票', content: '您可以在订单完成后，在订单详情页申请电子发票。' },
  { id: 'KB003', title: '关于运费的说明', content: '全场满99元包邮，不足将收取6元运费。' },
]);
const quickReplies = ref([
  { id: 1, content: '您好，请问有什么可以帮您？' },
  { id: 2, content: '您的问题已收到，我们会尽快处理。' },
  { id: 3, content: '感谢您的反馈，祝您生活愉快！' },
]);

const answerTypeMap: { [key: string]: string } = { text: '文本', kb: '知识库', quick: '快捷回复' };
const guideOptions = ['如何下单', '如何联系客服', '退货政策', '退款时效', '发票问题'];
const showRuleDialog = ref(false);
const editRuleForm = ref({ keyword: '', answerType: 'text', answer: '', guides: [] as string[] });
let editIndex = -1;
function editRule(row: any, idx: number) {
  editRuleForm.value = { ...row, guides: [...row.guides] };
  showRuleDialog.value = true;
  editIndex = idx;
}
function deleteRule(idx: number) {
  rules.value.splice(idx, 1);
}
function saveRule() {
  if (editIndex >= 0) {
    rules.value[editIndex] = { ...editRuleForm.value };
  } else {
    rules.value.push({ ...editRuleForm.value });
  }
  showRuleDialog.value = false;
  editIndex = -1;
  editRuleForm.value = { keyword: '', answerType: 'text', answer: '', guides: [] };
}

watch(() => editRuleForm.value.answerType, () => {
  editRuleForm.value.answer = '';
});

const scene = ref('pc');
const emojiList = ['😀','😂','😍','😢','😡','👍','👏','🎉','🥳','🤔','😎','😭','😅','😆','😏','😱','😴','😇','😜','🤗','😤'];
const showEmojiPanel = ref(false);
const imgInput = ref<HTMLInputElement | null>(null);
const audioInput = ref<HTMLInputElement | null>(null);
const videoInput = ref<HTMLInputElement | null>(null);

type ChatMsg = { from: string; text: string; type: string; url?: string; guides?: string[]; isWelcome?: boolean; isFallback?: boolean };
const chatHistory = ref<ChatMsg[]>([
  { from: 'robot', text: baseConfig.value.welcome, type: 'text', guides: [], isWelcome: true }
]);
const testInput = ref('');

function handleTest() {
  const input = testInput.value.trim();
  if (!input) return;
  chatHistory.value.push({ from: 'user', text: input, type: 'text' });
  // 简单模拟：关键词包含即命中
  const rule = rules.value.find(r => input.includes(r.keyword));
  if (rule) {
    chatHistory.value.push({ from: 'robot', text: rule.answer, type: 'text', guides: rule.guides });
  } else {
    chatHistory.value.push({ from: 'robot', text: baseConfig.value.fallback, type: 'text', guides: [], isFallback: true });
  }
  testInput.value = '';
  showEmojiPanel.value = false;
}
function sendEmoji(emoji: string) {
  chatHistory.value.push({ from: 'user', text: emoji, type: 'emoji' });
  showEmojiPanel.value = false;
}
function triggerImgUpload() { imgInput.value?.click(); }
function onImgChange(e: Event) {
  const files = (e.target as HTMLInputElement).files;
  if (files && files[0]) {
    const url = URL.createObjectURL(files[0]);
    chatHistory.value.push({ from: 'user', text: '', type: 'image', url });
  }
}
function triggerAudioUpload() { audioInput.value?.click(); }
function onAudioChange(e: Event) {
  const files = (e.target as HTMLInputElement).files;
  if (files && files[0]) {
    const url = URL.createObjectURL(files[0]);
    chatHistory.value.push({ from: 'user', text: '', type: 'audio', url });
  }
}
function triggerVideoUpload() { videoInput.value?.click(); }
function onVideoChange(e: Event) {
  const files = (e.target as HTMLInputElement).files;
  if (files && files[0]) {
    const url = URL.createObjectURL(files[0]);
    chatHistory.value.push({ from: 'user', text: '', type: 'video', url });
  }
}
function handleGuideClick(g: string) {
  testInput.value = g;
  handleTest();
}
function resetChat() {
  chatHistory.value = [
    { from: 'robot', text: baseConfig.value.welcome, type: 'text', guides: [], isWelcome: true }
  ];
  testInput.value = '';
}
</script>

<style scoped>
.robot-service-page {
  padding: 24px;
  background: #f7f8fa;
  min-height: 100vh;
}
.header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.settings-card, .rules-card, .test-card {
  margin-bottom: 18px;
}
.rules-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.editor-form-item {
  display: block !important;
}
.editor-form-item :deep(.el-form-item__label) {
  margin-bottom: 8px;
  padding-top: 0;
  align-self: unset;
}
.editor-form-item :deep(.ql-container) {
  min-height: 120px;
}
.test-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.chat-window {
  background: #f5f7fa;
  border-radius: 10px;
  padding: 18px 12px;
  min-height: 220px;
  max-height: 340px;
  overflow-y: auto;
  margin-bottom: 12px;
}
.chat-window.pc {
  width: 100%;
  min-width: 480px;
}
.chat-window.h5 {
  width: 340px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
}
.msg-row {
  display: flex;
  margin-bottom: 10px;
}
.msg-row.user {
  flex-direction: row-reverse;
}
.msg-bubble {
  max-width: 70%;
  background: #fff;
  border-radius: 16px;
  padding: 8px 14px;
  font-size: 15px;
  box-shadow: 0 1px 4px rgba(0,0,0,0.04);
  word-break: break-all;
  position: relative;
}
.msg-row.user .msg-bubble {
  background: #d2f9d1;
}
.guide-btns {
  margin-top: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.guide-btn {
  font-size: 13px;
  padding: 2px 10px;
}
.chat-input-bar {
  display: flex;
  align-items: center;
  gap: 8px;
}
.emoji-panel {
  position: absolute;
  bottom: 70px;
  left: 180px;
  background: #fff;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 8px 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  z-index: 10;
}
.emoji-item {
  font-size: 22px;
  cursor: pointer;
  padding: 2px 4px;
  border-radius: 4px;
  transition: background 0.15s;
}
.emoji-item:hover {
  background: #f0f0f0;
}
.emoji {
  font-size: 28px;
  line-height: 1.2;
}
.chat-img {
  max-width: 120px;
  max-height: 120px;
  border-radius: 6px;
  display: block;
}
.chat-audio {
  width: 120px;
  vertical-align: middle;
}
.chat-video {
  max-width: 180px;
  max-height: 120px;
  border-radius: 6px;
  display: block;
}
</style> 